<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\PaneltplAreaRequest;
use App\Models\Application\Paneltpl;
use App\Models\Application\PaneltplArea;
use App\Models\Operation\Meta;
use App\Repositories\Application\PaneltplAreaRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
use Validator;

class PaneltplAreaController extends Controller
{
    use ModelForm;

    /** @var  PaneltplAreaRepository */
    private $paneltplAreaRepository;

    public function __construct(PaneltplAreaRepository $paneltplAreaRepo)
    {
        $this->paneltplAreaRepository = $paneltplAreaRepo;
    }

    /**
     * Display a listing of the PaneltplArea.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $paneltplId = $request->input('paneltpl_id');
        if (!empty($paneltplId)) {
            $paneltpl = Paneltpl::find($paneltplId);

            if (empty($paneltpl)) {
                Flash::error(__('application.paneltpls.not_found'));
                return redirect(route('application.paneltpls.index'));
            }
            // 获取栏目推荐区位信息定义
            $panelAreas = PaneltplArea::where(['paneltpl_id' => $paneltplId])->get();
            if (empty($panelAreas->first())) {
                // 获取panel模板信息
                $paneltpl       = Paneltpl::where(['id' => $paneltplId])->first();
                $panelAreaDatas = [];
                $areas          = json_decode($paneltpl->areas, true);
                if (!empty($areas)) {
                    foreach ($areas as $key => $area) {
                        $panelAreaDatas[$key]['paneltpl_id'] = intval($paneltplId);
                        $panelAreaDatas[$key]['area']        = $area;
                        $panelAreaDatas[$key]['meta_id']     = 0;
                        $panelAreaDatas[$key]['ui']          = null;
                        $panelAreaDatas[$key]['onup']        = null;
                        $panelAreaDatas[$key]['ondown']      = null;
                        $panelAreaDatas[$key]['onleft']      = null;
                        $panelAreaDatas[$key]['onright']     = null;
                        $panelAreaDatas[$key]['options']     = null;
                        $panelAreaDatas[$key]['description'] = null;
                        $panelAreaDatas[$key]['created_at']  = date('Y-m-d H:i:s', time());
                    }
                }
                $result = DB::table('paneltpl_areas')->insert($panelAreaDatas);
                if (empty($result)) {
                    Flash::error(__('application.paneltpls.not_found'));

                    return redirect(route('application.paneltpls.index'));
                }
            }
        }
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('application.paneltpl_areas.index_header'));
            $content->description(__('application.paneltpl_areas.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new PaneltplArea.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.paneltpl_areas.create_header'));
            $content->description(__('application.paneltpl_areas.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created PaneltplArea in storage.
     *
     * @param PaneltplAreaRequest $request
     *
     * @return Response
     */
    public function store(PaneltplAreaRequest $request)
    {
        $input = $request->all();

        $image = $request->file('ui'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.paneltpl_area');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['ui'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $paneltplArea = $this->paneltplAreaRepository->create($input);

        Flash::success(__('application.paneltpl_areas.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.paneltpl_areas.index'));

    }

    /**
     * Display the specified PaneltplArea.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $paneltplArea = $this->paneltplAreaRepository->findWithoutFail($id);

        if (empty($paneltplArea)) {
            Flash::error(__('application.paneltpl_areas.not_found'));

            return redirect(route('application.paneltpl_areas.index'));
        }

        return view('application.paneltpl_areas.show')->with('paneltplArea', $paneltplArea);

    }

    /**
     * Show the form for editing the specified PaneltplArea.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.paneltpl_areas.edit_header'));
            $content->description(__('application.paneltpl_areas.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified PaneltplArea in storage.
     *
     * @param  int              $id
     * @param PaneltplAreaRequest $request
     *
     * @return Response
     */
    public function update($id, PaneltplAreaRequest $request)
    {
        $paneltplArea = $this->paneltplAreaRepository->findWithoutFail($id);

        if (empty($paneltplArea)) {
            Flash::error(__('application.paneltpl_areas.not_found'));

            return redirect(route('application.paneltpl_areas.index'));
        }
        $input = $request->all();

        // 如果删除原图
        if (array_key_exists('_file_del_', $input)) {

            $imgUrl       = $paneltplArea->ui;
            $uploadConfig = config('custom.base.upload.paneltpl_area');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $rootDir      = config('filesystems.disks.' . $driver . '.upload');
            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $paneltplArea->img = null;
                $paneltplArea->save();
            }
            return response()->json(['message' => '删除成功', 'status' => true]);
            return response()->json(['message' => '删除成功', 'status' => true]);
        }

        $sValidators = [
            'area'    => 'required|max:100',
            'meta_id' => 'required',
        ];

        $validators = [];

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), $validators, [
            'required' => ':attribute 不能为空',
        ], [
            // 'name'       => '名称',
            'meta_id' => 'meta模板',
        ]);

        if ($validator) {
            // 校验
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
        }

        $image = $request->file('ui'); //使用laravel 自带的request类来获取一下文件
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.paneltpl_area');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['ui'] = $fullPath;
                $flag        = Storage::disk($driver)->delete($paneltplArea->img);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $paneltplArea = $this->paneltplAreaRepository->update($input, $id);

        Flash::success(__('application.paneltpl_areas.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.paneltpl_areas.index'));
    }

    /**
     * Remove the specified PaneltplArea from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->paneltplAreaRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.paneltpl_areas.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $paneltplArea = $this->paneltplAreaRepository->findWithoutFail($id);

        if (empty($paneltplArea)) {
            Flash::error(__('application.paneltpl_areas.not_found'));

            return redirect(route('application.paneltpl_areas.index'));
        }

        if ($flag = $this->paneltplAreaRepository->delete($id)) {

            return response()->json(['message' => __('application.paneltpl_areas.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(PaneltplArea::class, function (Form $form) {

            $form->display('id', 'ID');
            $paneltpls = Paneltpl::pluck('name', 'id');
            $form->select('paneltpl_id', 'panel模板')->options($paneltpls);
            $form->text('area', '区位编号');
            $metas = Meta::pluck('name', 'id');
            $form->select('meta_id', 'mete模板')->options($metas);
            $form->image('ui', '区域视图')->removable();
            $form->text('onup', 'onup');
            $form->text('ondown', 'ondown');
            $form->text('onleft', 'onleft');
            $form->text('onright', 'onright');
            $form->text('options', 'options');
            $form->textarea('description', '说明');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(PaneltplArea::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');
            if (!empty($request->get('paneltpl_id'))) {
                $paneltplId = $request->get('paneltpl_id');
                $grid->model()->where(['paneltpl_id' => $paneltplId]);
            } else {
                $grid->model();

            }
            // // 添加按钮
            // if (!\Gate::check('application.paneltpl_areas.create')) {
                $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.paneltpl_areas.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.paneltpl_areas.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.paneltpl_areas.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            $grid->tools(function ($tools) {
                // $tools->batch(function ($batch) {
                //     // 批量删除按钮
                //     if (!\Gate::check('application.paneltpl_areas.batch_destroy')) {
                //         $batch->disableDelete();
                //     }
                // });
               $tools->append('<a href="javascript:void(0)" onclick="history.go(-1)" class="btn btn-default btn-sm" style="margin-right: 0px"> <i class="fa fa-arrow-left"></i>返回</a>');
            });

            // 添加按钮
            if (Admin::user()->cannot('application.paneltpl_areas.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('application.paneltpl_areas.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.paneltpl_areas.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('application.paneltpl_areas.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.paneltpl_areas.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('paneltpl.name', 'panel模板')->sortable();
            $grid->column('area', '区位编号')->sortable();
            $grid->column('meta.name', 'mete模板')->sortable();
            $uploadConfig = config('custom.base.upload.paneltpl_area');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('ui', '区域视图')->image($host);
            $grid->column('onup', 'onup')->sortable();
            $grid->column('ondown', 'ondown')->sortable();
            $grid->column('onleft', 'onleft')->sortable();
            $grid->column('onright', 'onright')->sortable();
            $grid->column('options', 'options')->sortable();
            $grid->column('description', '说明')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }
}
